package com.chpro.http.yixin.controller;

import com.chpro.common.DateUtil;
import com.chpro.common.StringUtil;
import com.chpro.http.yixin.receive.MsgModel;
import com.chpro.http.yixin.send.ResTxtMsgModel;
import com.chpro.http.yixin.verify.VerifyModel;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang.ObjectUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.chpro.common.JSONUtils;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;

/**
 * 易信消息接口
 * Created by Administrator on 14-9-27.
 */
@Controller
@RequestMapping("/easyMsg")
@Log4j
public class EasyMsgController {

    /**
     * 消息申请接口
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/applicationMessage",method= RequestMethod.GET)
    public String applicationMessage(VerifyModel verifyModel){
        log.info("进入易信申请消息接口");
        log.info("打印请求参数:"+ JSONUtils.toJSON(verifyModel));
        String result = verifyModel.verify();   //易信签名验证
        log.info("离开易信申请消息接口,返回result:"+result);
        return result;
    }

    /**
     * 消息接收
     * @return
     */
    @RequestMapping(value="/applicationMessage",method= RequestMethod.POST,produces = "plain/text; charset=UTF-8")
    public ResponseEntity<String>  receiveMessage(@RequestBody String requestBody)throws Exception{
        String result = "";
        log.info("进入易信接收消息接口");
        log.info("打印接收消息:"+ requestBody);
        MsgModel msgModel = MsgModel.toObject(requestBody);
        log.info("打印接收易信实体消息:"+ JSONUtils.toJSON(msgModel));
        if("text".equals(msgModel.getMsgType())){
            log.info("接收一个易信文件消息");
            ResTxtMsgModel resTxtMsgModel = new ResTxtMsgModel();
            resTxtMsgModel.setToUserName(msgModel.getFromUserName());   //设置收接方的帐号
            resTxtMsgModel.setFromUserName(msgModel.getToUserName());   //公众帐号ID
            resTxtMsgModel.setCreateTime(DateUtil.getCurrentDatetime()); //消息创建时间
            resTxtMsgModel.setMsgType("text");  //设置回复的消息类型
            resTxtMsgModel.setContent("这是一个普通的文本消息");   //设置内容
            result = resTxtMsgModel.toXml(resTxtMsgModel);
        }

        //解决JSON返回中文乱码问题
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType=new MediaType("text","html", Charset.forName("utf-8"));
        headers.setContentType(mediaType);
        ResponseEntity<String> responseEntity =new ResponseEntity<String>(result,headers, HttpStatus.OK);

        log.info("打印返回的消息:"+result);
        log.info("离开易信接收消息接口");
        return responseEntity;
    }
}
